<!-- 见证任务主页 -->
<template>
  <!-- 主页面，其它页面在里面对应渲染 -->
  <div class="layout-wrapper layout-row wintess-video">
    <v-video-sidebar class="app-sidebar layout-wrapper" :nav="navList" :openeds="openeds" @search="searchFn" />
    <div class="layout-wrapper">
      <v-header class="app-header" />
      <div class="app-main video-main">
        <!-- {{ navList }} -->
        <!-- 面包屑公共组件 -->
        <!-- 1. 这个面包屑组件是为了兼容之前页面跳转功能，页面重构时，这块再具体修改 -->
        <!-- <breadcrumb
          v-if="managerFlag"
          :showBackBtnFlag="managerFlag"
          @handleBack="toUrl"
        /> -->
        <!-- 2. 这个面包屑组价是默认的公共组件 -->
        <!-- <breadcrumb v-if="!managerFlag && usePublicBreadcrumbFlag" /> -->
        <v-main ref="videoMain" />
      </div>
    </div>
  </div>
</template>
<script>
  // Vue.prototype.$video = Video
  import header from "../../components/layout/header.vue";
  import videoSidebar from "../../components/layout/video-sidebar.vue";
  import main from "../../components/layout/video-main.vue";
  import { mapActions } from "vuex";
  import { loginIndexData, witnessItemRuleGetTime } from "../../api/api";
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  // import TabMenu from "../../../components/layout/components/tabMenu.vue";
  import { moduleInit, witnessMediaList } from "../../api/api.js";
  export default {
    // 引入组件
    components: {
      // TabMenu,
      "v-header": header,
      "v-main": main,
      "v-video-sidebar": videoSidebar
    },
    props: {},
    data() {
      // 这里存放数据
      return {
        navList: [],
        openeds: [],
        activeName: "Witnessing",
        tabList: [],
        MEDIAOBJ: {},
        industryTypeObj: {},
        witnessLinkObj: {} // 交易阶段
      };
    },
    watch: {
      navList(value) {
        this.SET_navlist(value);
      }
      // async openeds(value) {
      //   await this.SET_openeds(value);
      //   // this.$refs.videoMain.initVideo(0);
      // },
    },
    computed: {
      managerFlag() {
        return this.$store.getters.roles.some((item) => item.roleCode === "GDW_R_WITNESS_MANAGER");
        // return this.$store.getters.roleCode==="GDW_R_WITNESS_PERSON"
      }
    },
    beforeDestroy() {
      clearInterval(window.setIntervalFlag);
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
      localStorage.setItem("mediaFullPath", this.$route.fullPath);
      window.addEventListener("visibilitychange", () => {
        console.log(document.visibilityState);
        if (document.visibilityState === "hidden") {
          // 失去焦点
          console.log("hidden");
        } else {
          // 获取焦点
          // this.$route;
          console.log("this.$route", this.$route);
          const fullPath = localStorage.getItem("mediaFullPath");
          console.log("fullPath", fullPath);
          if (fullPath && fullPath !== this.$route.fullPath) {
            localStorage.setItem("mediaFullPath", this.$route.fullPath);
            document.location.reload();
          }
          console.log("this.$route", this.$route.fullPath);
        }
      });
      // 轮询监听
      if (!window.setIntervalFlag) {
        this.witnessItemRuleGetTimeFn();
      }
      clearInterval(window.setIntervalFlag);
      window.setIntervalFlag = setInterval(() => {
        this.witnessItemRuleGetTimeFn();
      }, 5000);
      this.initFn();
    },
    // 方法集合
    methods: {
      ...mapActions(["SET_navlist", "SET_openeds", "setSystemAction"]),
      async witnessItemRuleGetTimeFn() {
        try {
          await witnessItemRuleGetTime();
        } catch (error) {
          console.warn(error);
        }
      },
      async initFn() {
        await this.loginIndexDataFn();
        await this.moduleInitFn();
        await this.witnessMediaListFn();
      },
      async loginIndexDataFn() {
        try {
          const params = {
            systemCode: "WITNESS_SYSTEM"
          };
          const res = await loginIndexData(params);
          // console.log("loginIndexData", res);
          if (res.code === 0) {
            await this.setSystemAction({
              username: res.data.userName,
              userid: res.data.userId,
              systemname: res.data.systemName,
              identifyList: res.data.identifyList,
              roleCode: res.data.currentIdentify.roleCode,
              roleName: res.data.currentIdentify.roleName
            });
            sessionStorage.setItem("userId", res.data.userId);
          } else {
            this.$message({
              message: "获取系统数据失败",
              type: "error",
              duration: 1000,
              onClose: () => {
                this.$router.push({
                  name: "Login"
                });
              }
            });
          }
        } catch (e) {
          console.warn(e);
          this.$message({
            message: "登录初始化失败",
            type: "error",
            // iconClass: "el-icon-error"
            duration: 2000,
            onClose: () => {
              this.$router.push({
                name: "Login"
              });
            }
          });
        }
      },
      // 初始化模块
      async moduleInitFn() {
        const p = { moduleName: "MEDIA" };
        try {
          const res = await moduleInit(p);
          if (res.success) {
            this.MEDIAOBJ = res.data;
            // industryTypeAndIndustry
            // this.industryTypeObj ={};
            this.MEDIAOBJ.industryTypes.forEach((item) => {
              this.industryTypeObj[item.value] = item.label;
            });
            this.MEDIAOBJ.taskWitnessLinkAll.forEach((item) => {
              this.witnessLinkObj[item.value] = item.label;
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      handleSelect() {},
      searchFn(keyword) {
        console.log("keyword", keyword);
        this.keyword = keyword;
        clearTimeout(this.setFlag);
        this.setFlag = setTimeout(async () => {
          await this.witnessMediaListFn();
        }, 500);
      },
      industryTypeAndIndustryFn(key) {
        return this.industryTypeObj[key];
      },
      typeTagFn(key) {
        if (this.witnessLinkObj[key]) {
          return this.witnessLinkObj[key].replace("标", "");
        }
      },
      // 获取菜单数据
      async witnessMediaListFn() {
        this.navList = [];
        console.log("this.$route.query", this.$route.query);
        const { witnessSubTaskId } = this.$route.query;
        const { type } = this.$route.query;
        const p = {
          keyword: this.keyword
        };
        // if (this.managerFlag) {
        if (type === "over") {
          p.witnessSubTaskId = witnessSubTaskId;
        }
        if (this.$route.query.startTime) {
          p.startTime = this.$moment(new Date(+this.$route.query.startTime)).format("yyyy-MM-DD HH:mm:ss");
        }
        if (this.$route.query.endTime) {
          p.endTime = this.$moment(new Date(+this.$route.query.endTime)).format("yyyy-MM-DD HH:mm:ss");
        }
        try {
          const res = await witnessMediaList(p);
          const activeArr = [];
          const openedsFirstArr = [];
          if (res.success) {
            console.log("activeArraaaa", activeArr);
            if (res.data.projectList.length) {
              res.data.projectList.forEach((item) => {
                item.bidSectionList.forEach((itemB) => {
                  if (itemB.witnessSubTaskId === witnessSubTaskId) {
                    activeArr[0] = itemB.bidSectionCode;
                    activeArr[1] = itemB.witnessLinkCode;
                    activeArr[2] = item.projectCode;
                  }
                });
              });
              console.log("activeArraaaa", activeArr);
              const list = res.data.projectList.map((item) => ({
                title: item.projectName,
                id: item.projectId,
                industryTypeCode: item.industryType.toLowerCase(),
                industryTypeName: this.industryTypeAndIndustryFn(item.industryType),
                children: item.bidSectionList.map((cld) => {
                  if (!cld) {
                    return {};
                  }
                  return {
                    title: cld.bidSectionName,
                    path: cld.bidSectionCode,
                    id: cld.bidSectionUniqueId,
                    witnessLinkCode: cld.witnessLinkCode,
                    typeTag: this.typeTagFn(cld.witnessLinkCode),
                    children: cld.videoList.map((videoItem, k) => {
                      if (videoItem) {
                        if (!openedsFirstArr.length) {
                          openedsFirstArr.push(videoItem.id);
                        }
                        // if (1 || k < 1) {
                        if (
                          activeArr.length &&
                          activeArr[0] === cld.bidSectionCode &&
                          activeArr[1] === cld.witnessLinkCode &&
                          activeArr[2] === item.projectCode
                        ) {
                          this.openeds.push(videoItem.id);
                        }
                        // }
                        return {
                          title: `${item.projectName}-${cld.bidSectionName}-${videoItem.name}`,
                          path: videoItem.url,
                          id: videoItem.id,
                          videoType: videoItem.videoType,
                          children: null
                        };
                      }
                      return {};
                    })
                  };
                })
              }));
              this.$set(this, "navList", list);
            } else {
              this.openeds = [];
            }
            this.SET_openeds(this.openeds);
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.warn(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .wintess-video {
    background-color: #29384b;
    .app-sidebar {
      width: 307px;
      background-color: #364860;
    }
    .app-main {
      background-color: #29384b;
      margin: 0;
      display: flex;
      flex-direction: column;
      max-width: 1600px;
    }
  }
</style>
